/**
 * 2013 2013-5-15
 */
package com.surfilter.platform.base.servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
 *
 */
public class ExcelGenServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	
	/**
	 * 处理请求数据，生成Excel文件，提供客户端下载
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String records = request.getParameter("records") ;
		String title = request.getParameter("title");
		String header = request.getParameter("header");
		JSONArray recordsArray = JSONArray.fromObject(records);
		JSONArray headerArray = JSONArray.fromObject(header);
		HSSFWorkbook wb = genExcelFile(recordsArray,headerArray,title);
		response.reset();
		response.setContentType("application/vnd.ms-excel");
		String fileName = URLEncoder.encode(title, "UTF-8") + "_" + new SimpleDateFormat("yyyy-MM-dd HH_mm_ss").format(new Date()) + ".xls";
		response.setHeader("Content-Disposition", "attachment;filename=\""+fileName+"\"");
		ServletOutputStream sos = response.getOutputStream();
		wb.write(sos);
		sos.close();
		response.flushBuffer();
	}
	
	/**
	 * 更具表头和记录信息生成Excel
	 * @param records
	 * @param header
	 * @param title
	 * @return
	 */
	private HSSFWorkbook genExcelFile (JSONArray records,JSONArray header,String title){
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(title);
		//填充表头
		HSSFRow headerRow = sheet.createRow(0);
		for (int i = 0; i < header.size(); i++) {
			HSSFCell headerCell = headerRow.createCell(i);
			headerCell.setCellValue(new HSSFRichTextString(header.getString(i)));
		}
		//填充其他数据
		for(int i = 0; i<records.size(); i++){
			JSONArray record = JSONArray.fromObject(records.get(i));
			HSSFRow dataRow = sheet.createRow(i+1);
			for(int j = 0 ; j<header.size();j++){
				String fieldRecord = "null".equals(record.getString(j))?"":record.getString(j);
				HSSFCell dataCell = dataRow.createCell(j);
				dataCell.setCellValue(new HSSFRichTextString(fieldRecord));
			}
		}
		return wb;
	}
	
	
}
